package com.regex.web.controller.szclnf;


import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.regex.web.common.excel.ExportExcel;
import com.regex.web.common.excel.ImportExcel;
import com.regex.web.entity.szclnf.SzclAcceptZsjv4103527DTO;
import com.regex.web.entity.szclnf.SzclZzcjrDTO;
import com.regex.web.service.szclnf.ISzclAcceptZsjv4103527Service;
import com.regex.web.service.szclnf.ISzclZzcjrService;
import com.regex.web.utils.AjaxUtil;
import com.regex.web.utils.Contant;
import com.regex.web.utils.QueryResult;
import com.regex.web.vo.ImportResultVO;
import com.regex.web.vo.LayTableDataVO;
import com.regex.web.vo.ResultVO;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zzl
 * @since 2021-07-13
 */
@Controller
@RequestMapping("sys/szclAcceptZsjv4103527")
public class SzclAcceptZsjv4103527Controller {

	private final static Logger logger = LoggerFactory.getLogger(SzclAcceptZsjv4103527Controller.class);
	
	@Autowired
	private ISzclAcceptZsjv4103527Service ISzclAcceptZsjv4103527Service;
	
	@Autowired
	private ISzclZzcjrService ISzclZzcjrService;
	
	/**
	 * 分页查询
	 * @param page
	 * @param model
	 * @param szclAcceptZsjv4103527DTO
	 * @return
	 */
	@GetMapping("show")
	public String show() {
		return "sys/szclAcceptZsjv4103527/show";
	}
	
	@GetMapping("getall")
	@ResponseBody
	public List<SzclAcceptZsjv4103527DTO> getall() {
		 QueryWrapper<SzclAcceptZsjv4103527DTO> param = new QueryWrapper<SzclAcceptZsjv4103527DTO>();
			param.eq("TASKNAME", "用人单位分散按比例安排残疾人就业年度审核");
		List<SzclAcceptZsjv4103527DTO> list=ISzclAcceptZsjv4103527Service.list(param);
		List<SzclZzcjrDTO> list1=ISzclZzcjrService.list();
		String arr="";
		for (int i = 0; i < list1.size(); i++) {
			arr=arr+","+list1.get(i).getSfzh();
		}
		for(int z=0;z<list.size();z++){
				System.out.println(list.get(z));
				System.out.println("字符集=="+list.get(z).getApplyform());
				JSONObject jsonObject = JSON.parseObject(list.get(z).getApplyform()); // JSONObject
		
			JSONArray jsonArrayData = jsonObject.getJSONArray("drow20181999103670645");
			int sizes = jsonArrayData.size();
			for (int j = 0; j < sizes; j++) {
				SzclZzcjrDTO szclZzcjrDTO=new SzclZzcjrDTO();
				JSONObject jsonObjectData = jsonArrayData.getJSONObject(j);
				System.out.println(z+"残疾人身份证号"+jsonObjectData.getString("ShenFenZhengHao"));
				szclZzcjrDTO.setXm(jsonObjectData.getString("XingMing"));
				szclZzcjrDTO.setXb(jsonObjectData.getString("XingBie"));
				szclZzcjrDTO.setSfzh(jsonObjectData.getString("ShenFenZhengHao"));
				szclZzcjrDTO.setFzsj(jsonObjectData.getString("FaZhengShiJian"));
				szclZzcjrDTO.setHjlx(jsonObjectData.getString("HuJiLeiXing"));
				szclZzcjrDTO.setCjdj(jsonObjectData.getString("JunCanDengJ"));
				szclZzcjrDTO.setHyzk(jsonObjectData.getString("HunYinZhuangKuang"));
				szclZzcjrDTO.setGwmc1(jsonObjectData.getString("gwmc1"));
				szclZzcjrDTO.setGwmc(jsonObjectData.getString("GangWeiMingChen"));
				szclZzcjrDTO.setGwmc2(jsonObjectData.getString("gwmc2"));
				szclZzcjrDTO.setGwmc3(jsonObjectData.getString("gwmc3"));
				szclZzcjrDTO.setD2gwmc(jsonObjectData.getString("GangWeiMingChen2"));
				szclZzcjrDTO.setD3gwmc(jsonObjectData.getString("GangWeiMingChen3"));
				szclZzcjrDTO.setWhcd(jsonObjectData.getString("WenHuaChengDu"));
				szclZzcjrDTO.setSbdnh(jsonObjectData.getString("SheBaoDianNaoHao"));
				szclZzcjrDTO.setZt(jsonObjectData.getString("ZhuangTai"));
				szclZzcjrDTO.setZgqk(jsonObjectData.getString("ZaiGangQingKuang"));
				szclZzcjrDTO.setJyyf(jsonObjectData.getString("JiuYeYueFen"));
				szclZzcjrDTO.setBdwjyqssj(jsonObjectData.getString("BenDanWeiJiuYeQiShiShiJian"));
				szclZzcjrDTO.setJjlxrdh(jsonObjectData.getString("JinJiLianXiRenDianHua"));
				szclZzcjrDTO.setZcdj(jsonObjectData.getString("ZhiChenDengJi"));
				szclZzcjrDTO.setJzzh(jsonObjectData.getString("JunCanZhengHao"));
				szclZzcjrDTO.setHkdz(jsonObjectData.getString("HuKouDiZhi"));
				szclZzcjrDTO.setDynWidgetName(jsonObjectData.getString("dynWidgetName"));
				szclZzcjrDTO.setMz(jsonObjectData.getString("MinZu"));
				szclZzcjrDTO.setJg(jsonObjectData.getString("JiGuan"));
				
				szclZzcjrDTO.setJjlxrxm(jsonObjectData.getString("JinJiLianXiRenXingMing"));
				szclZzcjrDTO.setCjdj(jsonObjectData.getString("CanJiDengJi"));
				szclZzcjrDTO.setAhtc(jsonObjectData.getString("AiHaoTeChang"));
				szclZzcjrDTO.setJtzz(jsonObjectData.getString("JiaTingZhuZhi"));
				szclZzcjrDTO.setSfjc(jsonObjectData.getString("ShiFuJunCan"));
				szclZzcjrDTO.setCsrq(jsonObjectData.getString("ChuShengRiQi"));
				szclZzcjrDTO.setCjlb(jsonObjectData.getString("CanJiLeiBie"));
				szclZzcjrDTO.setLxdh(jsonObjectData.getString("DianHuaLianXi"));
				szclZzcjrDTO.setCjzh(jsonObjectData.getString("CanJiRenZhengHao"));
				szclZzcjrDTO.setYsr(jsonObjectData.getString("YueShouRu"));
				szclZzcjrDTO.setTbsj(list.get(z).getCdTime());
				
				szclZzcjrDTO.setIsDel(Contant.is_del_undelete);
				szclZzcjrDTO.setUpdateTime(new Date());
				szclZzcjrDTO.setCreateTime(new Date());
				boolean flag = false;
				boolean status = arr.contains(szclZzcjrDTO.getSfzh());
				if(status){
					//数据库已有
					Map<String, Object> map=new HashMap<>();
					map.put("sfzh", szclZzcjrDTO.getSfzh());
					flag=ISzclZzcjrService.updateZzcjr(map);
				}else{
					flag = ISzclZzcjrService.save(szclZzcjrDTO);
				}
			}
		
		}
		
		
		return list;
	}
	
	@RequestMapping("getPageData")
	public void getPageData(HttpServletResponse response,
			SzclAcceptZsjv4103527DTO szclAcceptZsjv4103527DTO, String limit, String page) {
		LayTableDataVO<SzclAcceptZsjv4103527DTO> result = new LayTableDataVO<SzclAcceptZsjv4103527DTO>();
		try {
			
			QueryWrapper<SzclAcceptZsjv4103527DTO> param = new QueryWrapper<SzclAcceptZsjv4103527DTO>();
			param.orderByDesc("create_time");
			Page<SzclAcceptZsjv4103527DTO> pageParam = new Page<SzclAcceptZsjv4103527DTO>();
			if (StringUtils.isEmpty(limit)) {
				limit = Contant.NONMAL_PAGE_SIZE_TEN + "";
			}
			if (StringUtils.isEmpty(page)) {
				page = Contant.NONMAL_PAGE_START + "";
			}
			pageParam.setSize(Integer.parseInt(limit));
			pageParam.setCurrent(Integer.parseInt(page));
			
	        QueryResult<SzclAcceptZsjv4103527DTO> pageResult = ISzclAcceptZsjv4103527Service.page(pageParam, param);
			
			result.setData(pageResult.getDatas());
			result.setCode(0);
			result.setCount(pageResult.getTotalDataCount());
		} catch (Exception e) {
			result.setCode(500);
			AjaxUtil.ajaxJsonSucMessage(response, result);
			e.printStackTrace();
		}
		AjaxUtil.ajaxJsonSucMessage(response, result);
	}
	
	/**
	 * 编辑/新增
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("input")
    public String toSave(@ModelAttribute("id")  String id) {
        return "sys/szclAcceptZsjv4103527/input";
    }
    
    @GetMapping("get/{id}")
	@ResponseBody
    public ResultVO<SzclAcceptZsjv4103527DTO> getData(@PathVariable String id) {
	    SzclAcceptZsjv4103527DTO szclAcceptZsjv4103527DTO = ISzclAcceptZsjv4103527Service.getById(id);
        return ResultVO.success(szclAcceptZsjv4103527DTO, ResultVO.SUCCESS, ResultVO.errors.get(ResultVO.SUCCESS));
    }
    
    /**
	 * 保存
	 * @param szclAcceptZsjv4103527DTO
	 * @param response
	 */
    @PostMapping("save")
	@ResponseBody
	public ResultVO<String> save(@Valid  @RequestBody SzclAcceptZsjv4103527DTO szclAcceptZsjv4103527DTO, HttpServletResponse response) {
		ResultVO<String> result = new ResultVO<String>();
		boolean flag = false;
		if(StringUtils.isNotEmpty(szclAcceptZsjv4103527DTO.getId())) {
			szclAcceptZsjv4103527DTO.setUpdateTime(new Date());
			flag = ISzclAcceptZsjv4103527Service.updateById(szclAcceptZsjv4103527DTO);
			if(flag) {
            	return ResultVO.success();
            }
		} else {
			szclAcceptZsjv4103527DTO.setIsDel(Contant.is_del_undelete);
			szclAcceptZsjv4103527DTO.setUpdateTime(new Date());
			szclAcceptZsjv4103527DTO.setCreateTime(new Date());
			flag = ISzclAcceptZsjv4103527Service.save(szclAcceptZsjv4103527DTO);
			if(flag) {
            	return ResultVO.success();
            }
		}
		return result;
	}
	
	/**
	 * 详情
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("detial")
    public String detial(String id, Model model) {
        try {
	        if(StringUtils.isNotEmpty(id)) {
	        	SzclAcceptZsjv4103527DTO szclAcceptZsjv4103527DTO = ISzclAcceptZsjv4103527Service.getById(id);
	            model.addAttribute("szclAcceptZsjv4103527DTO", szclAcceptZsjv4103527DTO);
	        }
        } catch (Exception e) {
			e.printStackTrace();
			logger.error("detial page is Exception!");
		}
        return "sys/szclAcceptZsjv4103527/detial";
    }
	
	/**
	 * 删除
	 * @param id
	 * @param response
	 */
	@RequestMapping("del")
    public void del(String id, HttpServletResponse response) {
        int n = 0;
        try {
	        if(StringUtils.isNotEmpty(id)) {
	        	boolean flag = ISzclAcceptZsjv4103527Service.removeById(id);
	        	if(flag) {
	        		n = 1;
	        	}
	        } else {
	        	n = 2;
	        }
        } catch (Exception e) {
			e.printStackTrace();
			logger.error("del page is Exception!");
		}
        AjaxUtil.ajaxJsonSucMessage(response, n);
    }
    
    /**
	 * 导出
	 * @param response
	 * @param szclAcceptZsjv4103527DTO
	 * @return
	 */
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(HttpServletResponse response, @ModelAttribute("szclAcceptZsjv4103527DTO") SzclAcceptZsjv4103527DTO szclAcceptZsjv4103527DTO) {
        try {
            QueryWrapper<SzclAcceptZsjv4103527DTO> param = new QueryWrapper<SzclAcceptZsjv4103527DTO>();
			param.orderByDesc("create_time");
        	String fileName = "数据"+(new Date()).getTime()+".xlsx";
            
            List<SzclAcceptZsjv4103527DTO> datas = ISzclAcceptZsjv4103527Service.list(param);
            new ExportExcel("数据", SzclAcceptZsjv4103527DTO.class).setDataList(datas).write(response, fileName).dispose();
            return null; 
        } catch (Exception e) {
        	logger.error("exportFile page is Exception!");
            e.printStackTrace();
        }
        return "redirect:show.htm";
    }
    
    
     /**
     * 
     * 功能描述: <br>
     * 下载导入模板
     *
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "importTemplate")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "信息导入模板.xlsx";
            List<SzclAcceptZsjv4103527DTO> list = new ArrayList<>(); 
            list.add(new SzclAcceptZsjv4103527DTO());
            new ExportExcel("信息数据", SzclAcceptZsjv4103527DTO.class, 2).setDataList(list).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/sys/szclAcceptZsjv4103527/show";
    }

    
    /**
     * 
     * 功能描述: <br>
     * 去导入界面
     *
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @GetMapping("toImport")
    public String toImport() {
        return "sys/szclAcceptZsjv4103527/import_excel";
    }
    
    /**
     * 
     * 功能描述: <br>
     * 导入
     *
     * @param file
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("importFile")
    @ResponseBody
    public ResultVO<ImportResultVO> importFile(MultipartFile file, @RequestParam(required = false, value="param") String param) {
        JSONObject json = JSON.parseObject(param);
        logger.error(json!=null?json.toJSONString():"");
        int successNum=0;
        int failureNum=0;
        StringBuilder failureMsg=new StringBuilder();
        ImportExcel ei;
        List<SzclAcceptZsjv4103527DTO> list;
        try {
            ei = new ImportExcel(file, 1, 0);
            list=ei.getDataList(SzclAcceptZsjv4103527DTO.class);
        } catch (Exception e1) {
            e1.printStackTrace();
            list = new ArrayList<>(); 
        }
        for(SzclAcceptZsjv4103527DTO data : list) {
               data.setUpdateTime(new Date());
               data.setIsDel(Contant.is_del_undelete);
               data.setCreateTime(new Date());
               try {
                   ISzclAcceptZsjv4103527Service.saveOrUpdate(data);
                   successNum++;
               } catch (Exception e) {
                   e.printStackTrace();
                   failureNum++;
                   failureMsg.append("数据：").append(JSON.toJSONString(data)).append("导入失败；");
               }
        }
        return ResultVO.success(ImportResultVO.result(successNum, failureNum, failureMsg.toString()), ResultVO.SUCCESS, ResultVO.errors.get(ResultVO.SUCCESS));
    }
	
}
